// LibraryDataService.java - 修改为使用数据库
package com.library.service;

import com.library.entity.*;
import com.library.dao.BookDAO;
import com.library.dao.ReaderDAO;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class LibraryDataService {
    private Map<String, Book> books; // ISBN -> Book (内存缓存)
    private Map<String, Reader> readers; // ReaderId -> Reader (内存缓存)
    private Map<Reader.ReaderType, BorrowRule> borrowRules;

    private BookDAO bookDAO;
    private ReaderDAO readerDAO;

    public LibraryDataService() {
        this.books = new ConcurrentHashMap<>();
        this.readers = new ConcurrentHashMap<>();
        this.borrowRules = new ConcurrentHashMap<>();

        this.bookDAO = new BookDAO();
        this.readerDAO = new ReaderDAO();

        // 从数据库加载数据到内存缓存
        loadDataFromDatabase();
        initializeDefaultRules();
    }

    /**
     * 从数据库加载数据到内存缓存
     */
    private void loadDataFromDatabase() {
        loadBooksFromDB();
        loadReadersFromDB();
    }

    /**
     * 从数据库加载图书数据到内存
     */
    private void loadBooksFromDB() {
        books.clear();
        List<Book> bookList = bookDAO.getAllBooks();
        for (Book book : bookList) {
            books.put(book.getIsbn(), book);
        }
        System.out.println("内存中加载 " + books.size() + " 本图书");
    }

    /**
     * 从数据库加载读者数据到内存
     */
    private void loadReadersFromDB() {
        readers.clear();
        List<Reader> readerList = readerDAO.getAllReaders();
        for (Reader reader : readerList) {
            readers.put(reader.getReaderId(), reader);
        }
        System.out.println("内存中加载 " + readers.size() + " 位读者");
    }

    /**
     * 刷新图书数据（从数据库重新加载）
     */
    public void refreshBooks() {
        loadBooksFromDB();
    }

    /**
     * 刷新读者数据（从数据库重新加载）
     */
    public void refreshReaders() {
        loadReadersFromDB();
    }

    private void initializeDefaultRules() {
        // 初始化默认借阅规则
        borrowRules.put(Reader.ReaderType.STUDENT,
                new BorrowRule(Reader.ReaderType.STUDENT, 10, 30, 1, true, 3, 0.1));
        borrowRules.put(Reader.ReaderType.TEACHER,
                new BorrowRule(Reader.ReaderType.TEACHER, 20, 60, 2, true, 5, 0.05));
        borrowRules.put(Reader.ReaderType.STAFF,
                new BorrowRule(Reader.ReaderType.STAFF, 15, 45, 2, true, 4, 0.08));
        borrowRules.put(Reader.ReaderType.EXTERNAL,
                new BorrowRule(Reader.ReaderType.EXTERNAL, 5, 21, 0, false, 0, 0.2));
    }

    // 图书管理方法
    public boolean addBook(Book book) {
        // 先保存到数据库
        boolean dbSuccess = bookDAO.addBook(book);
        if (dbSuccess) {
            // 如果数据库保存成功，更新内存缓存
            books.put(book.getIsbn(), book);
            return true;
        }
        return false;
    }

    public boolean updateBook(Book book) {
        // 先更新数据库
        boolean dbSuccess = bookDAO.updateBook(book);
        if (dbSuccess) {
            // 如果数据库更新成功，更新内存缓存
            books.put(book.getIsbn(), book);
            return true;
        }
        return false;
    }

    public boolean deleteBook(String isbn) {
        // 先从数据库删除
        boolean dbSuccess = bookDAO.deleteBook(isbn);
        if (dbSuccess) {
            // 如果数据库删除成功，更新内存缓存
            books.remove(isbn);
            return true;
        }
        return false;
    }

    public Book findBookByIsbn(String isbn) {
        // 先从内存缓存查找
        Book book = books.get(isbn);
        if (book == null) {
            // 如果内存中没有，从数据库查找
            book = bookDAO.getBookByIsbn(isbn);
            if (book != null) {
                books.put(isbn, book); // 添加到内存缓存
            }
        }
        return book;
    }

    public List<Book> searchBooks(String keyword) {
        // 直接调用DAO进行搜索，确保数据最新
        return bookDAO.searchBooks(keyword);
    }

    public List<Book> getAllBooks() {
        // 直接调用DAO获取所有图书，确保数据最新
        return bookDAO.getAllBooks();
    }

    // 读者管理方法
    public boolean addReader(Reader reader) {
        // 先保存到数据库
        boolean dbSuccess = readerDAO.addReader(reader);
        if (dbSuccess) {
            // 如果数据库保存成功，更新内存缓存
            readers.put(reader.getReaderId(), reader);
            return true;
        }
        return false;
    }

    public boolean updateReader(Reader reader) {
        // 先更新数据库
        boolean dbSuccess = readerDAO.updateReader(reader);
        if (dbSuccess) {
            // 如果数据库更新成功，更新内存缓存
            readers.put(reader.getReaderId(), reader);
            return true;
        }
        return false;
    }

    public boolean deleteReader(String readerId) {
        // 先从数据库删除
        boolean dbSuccess = readerDAO.deleteReader(readerId);
        if (dbSuccess) {
            // 如果数据库删除成功，更新内存缓存
            readers.remove(readerId);
            return true;
        }
        return false;
    }

    public Reader findReaderById(String readerId) {
        // 先从内存缓存查找
        Reader reader = readers.get(readerId);
        if (reader == null) {
            // 如果内存中没有，从数据库查找
            reader = readerDAO.getReaderById(readerId);
            if (reader != null) {
                readers.put(readerId, reader); // 添加到内存缓存
            }
        }
        return reader;
    }

    public List<Reader> searchReaders(String keyword) {
        // 直接调用DAO进行搜索，确保数据最新
        return readerDAO.searchReaders(keyword);
    }

    public List<Reader> getAllReaders() {
        // 直接调用DAO获取所有读者，确保数据最新
        return readerDAO.getAllReaders();
    }

    // 借阅规则管理方法
    public BorrowRule getBorrowRule(Reader.ReaderType type) {
        return borrowRules.get(type);
    }

    public boolean updateBorrowRule(BorrowRule rule) {
        borrowRules.put(rule.getReaderType(), rule);
        return true;
    }

    public Map<Reader.ReaderType, BorrowRule> getAllBorrowRules() {
        return new HashMap<>(borrowRules);
    }

    // 数据统计方法
    public int getTotalBookCount() {
        return books.size();
    }

    public int getTotalReaderCount() {
        return readers.size();
    }

    public Map<String, Integer> getBooksByCategory() {
        return bookDAO.getBooksByCategory();
    }

    /**
     * 获取热门图书
     */
    public List<Book> getPopularBooks(int limit) {
        return bookDAO.getPopularBooks(limit);
    }
}